let init = () => {
    initEvent()
    isShowLikeNum()
    sessionStorage.getItem('userToken') && initUeditor()
}

function initUeditor() {
    window.editor = new wangEditor('editor-trigger');
    editor.config.menus = [
        'bold',
        'underline',
        'italic',
        'strikethrough',
        'eraser',
        'forecolor',
        'bgcolor',
        'fontsize',
        'alignleft',
        'aligncenter',
        'alignright',
        'link',
        'emotion',
        'location',
        'insertcode',
        'fullscreen'
    ];
    editor.create();
}

let isShowLikeNum = () => {
    $('.like-num').each((index, item) => {
        if ($(item).html() == 0) {
            $(item).hide().siblings('.icon-like').hide()
        } else {
            $(item).show().siblings('.icon-like').show()
        }
    })
}

$('.list-item').hover(function() {
    let $this = $(this)
    let $likeIcon = $this.find('.icon-like')
    let n = $this.find('.like-num').html()
    if (n < 1) {
        $likeIcon.show()
    }
}, function() {
    let $this = $(this)
    let $likeIcon = $this.find('.icon-like')
    let n = $this.find('.like-num').html()
    if (n < 1) {
        $likeIcon.hide()
    }
})

function initEvent() {
    $('#callbackBtn').on('click', onSendCallBackBtnClick)
    $('.icon-like').on('click', onchangeLikeClick)
}

//发布评论
let onSendCallBackBtnClick = async function() {
    let article_id = location.href.substr(location.href.lastIndexOf('/') + 1)
    let rating_txt = editor.$txt.html()
    let postRatingsStatus = await sendRatings({
        article_id,
        rating_txt
    })
    if (postRatingsStatus.code == 0) {
        alert('发布成功')
        location.reload()
    }
}

//点赞事件
let onchangeLikeClick = async function() {
    if (!sessionStorage.getItem('userToken')) {
        alert('必须登陆才能进行点赞')
        return
    }

    let $this = $(this)
    let flag = null
    let $likeNum = $this.siblings('.like-num')
    let n = $likeNum.html()

    $this.toggleClass('is-show');
    (flag = $this.hasClass('is-show')) ? ++n: --n

    $likeNum
        .html(n)
        .html() == 0 ? $likeNum.hide() : $likeNum.show()

    await saveLikeNum({
        _id: this.id,
        flag
    })
}





init()